﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Windows;
using System.Runtime.InteropServices;
using Microsoft.Practices.ServiceLocation;
using Microsoft.Practices.Unity;
using XbdSoft.WPFVersion.ViewModel;
using XbdSoft.Client;
using XbdSoft.Contract;
using System.Diagnostics;
using XbdSoft.Domain;
using System.Data.Entity;
using System.Net;

namespace XbdSoft.WPFVersion
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : Application
    {
        public const string AutoUpdateExeFileName = "小布叮自动更新.exe";

        #region Resources
        //http://www.switchonthecode.com/tutorials/the-wpf-tab-control-inside-and-out  tab style
        //http://blog.csdn.net/nanchuan/archive/2011/05/21/6436836.aspx  log
        //http://msdn.microsoft.com/zh-cn/library/aa348549.aspx message 
        // http://hi.baidu.com/5ihuige/blog/item/4e0556b380dc3a42082302a6.html http request

//        搜索关键字唯空的时，classid=151 '分类记录获取sql，151为所有分类
//sql="select top 20000 A.ArticleID,A.ClassID,C.ClassName,A.Title,A.fileurl,A.KeyV108,A.Author,A.CopyFrom,A.UpdateTime,A.Editor,"
//sql=sql & "A.Hits,A.OnTop,A.Hot,A.Elite,A.Passed,A.IncludePic,A.Stars,A.PaginationType,A.ReadLevel,A.ReadPoint from Article1 A"
//sql=sql & " inner join ArticleClass1 C on A.ClassID=C.ClassID where A.Deleted=0"
//if ClassID>0 then
//    if classid=151 then
//        ChildID=""
//        set tClass=conn.execute("select classid From ArticleClass1 where parentid=151 and isElite=1 and showontop=1")
//        do while not tClass.eof
//            if ChildID="" then
//                ChildID=tClass(0)
//            else
//                ChildID=ChildID & "," & tClass(0)
//            end if
//            tClass.movenext
//        loop
//        sql=sql & " and A.ClassID in (" & ChildID & ")"
//    else
//        sql=sql & " and A.ClassID=" & ClassID
//    end if

//end if
//sql=sql & " order by A.ArticleID desc"

        #endregion

        //fffff        //5583440

        #region Ctor
        public App()
        {
            //CheckService();

            ServicePointManager.DefaultConnectionLimit = Util.DefaultConnectionLimit;
            // ServicePointManager.SetTcpKeepAlive(true, 1000000, 2000);

            //if (HasNewVersion() && MessageBox.Show("小布叮有新的版本需要更新，您确定要更新吗？", "自动更新程序", MessageBoxButton.OKCancel) == MessageBoxResult.OK)
            //{
            //    UpdateLatestVersion();
            //}

            var bootStrapper = new Bootstrapper();
            bootStrapper.InitializeDownloadID = downloadID;
            bootStrapper.Run();
        }
        #endregion

        protected int downloadID = 0;
        protected override void OnStartup(StartupEventArgs e)
        {
            if (e.Args != null && e.Args.Length > 0)
            {
                downloadID = Convert.ToInt32(e.Args[0]);
            }
            base.OnStartup(e);
        }

        #region Check Version

        private bool HasNewVersion()
        {
            bool isLatestVersion = false;
            var currentVersion = Application.ResourceAssembly.GetName().Version;
            try
            {
                using (var autoUpdateService = new ServiceObject<IAutoUpdateService>(Util.AutoUpdateServiceAddress))
                {
                    var latestVersionStr = autoUpdateService.Object.GetLatestVersion();
                    if (!String.IsNullOrWhiteSpace(latestVersionStr))
                    {
                        var latestVersion = new Version(latestVersionStr);
                        isLatestVersion = latestVersion.CompareTo(currentVersion) > 0;
                    }
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show(ex.Message);
            }
            return isLatestVersion;
        }

        private void UpdateLatestVersion()
        {
            try
            {
                var autoUpdateExeFile = System.IO.Path.Combine(Environment.CurrentDirectory, AutoUpdateExeFileName);
                if (!System.IO.File.Exists(autoUpdateExeFile))
                {
                    MessageBox.Show(string.Format("对不起，没有找到更新程序：{0}", AutoUpdateExeFileName));
                }
                else
                {
                    var zipFile = string.Empty;
                    using (var service = new ServiceObject<IAutoUpdateService>(Util.AutoUpdateServiceAddress))
                    {
                        zipFile = service.Object.GetDefaultSetupFileUrl();
                    }
                    Process.Start(autoUpdateExeFile,zipFile);
                    Process.GetCurrentProcess().Kill();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message );
            }
        }

        protected void CheckService()
        {
            var canOpen = true;
            try
            {
                using (var service = new ServiceObject<IDownloadService>(Util.DownloadServiceAddress))
                {
                    //service.CanOpen();
                    var url = service.Object.GetDownloadInfoUrl();
                    canOpen = !string.IsNullOrEmpty(url);
                    //var dd = service.Object.GetDownloadInfoUrl();
                }
            }
            catch (Exception e)
            {
                canOpen = false;
                MessageBox.Show(e.Message);
            }
            if (!canOpen)
            {
                MessageBox.Show("对不起，网络连接或者服务器端异常，不能打开软件。");
                Process.GetCurrentProcess().Kill();
            }
        }
        #endregion

    }
}
